import * as React from 'react';
import { Modal,View, Text, TouchableOpacity, useWindowDimensions, StyleSheet, Animated, ScrollView, Image, ViewStyle} from 'react-native';
import { TabView, SceneMap } from 'react-native-tab-view';
import {scaleSize} from "@/utils/screenSize";
import {router, Stack, useRouter} from "expo-router";
import AntDesign from "@expo/vector-icons/AntDesign";
import avator from "@/assets/images/me/avator.png";
import {forwardRef, useCallback, useEffect, useImperativeHandle, useState} from "react";
import empty_fan from "@/assets/images/concern/empty_fan.png"
import CheckBox from '@react-native-community/checkbox';
import TarjectoryActivityList from "@/components/TarjectoryActivityList";
import {format} from "date-fns/index";
import {getRecommendationsList} from "@/services/activityServices";
import {calculateTotalPages} from "@/utils";
import {hidden} from "colorette";
import {useSelector} from "react-redux";
import {RootState} from "@/store";
import {getSpaceSearchByRequest} from "@/services/spaceServices";
import CustomFlatList from "@/components/CustomFlatList";
import {getSearchCoummunityListByRequest} from "@/services/registerCommumity";
import CarouselComponent from "@/components/CarouselComponent";
import SwiperActivityItemComponent from "@/components/SwiperActivityItem";

const fanRoute = () => {
    const [cancelConcern, setCancelConcern] = useState(false);
    const [length, setLength] = useState(10);
    const [recommentList, setRecommentList] = useState<any[]>([]);
    const [current, setCurrent] = useState(1);
    const [size, setSize] = useState(10);
    const [pages, setPages] = useState(0);

    useEffect(() => {
        getRecommentList();
    }, [])

    const getRecommentList = function (params?: any = {}, refreshing, setRefreshing, noMore) {
        const data = {
            typeId: "2",
            province: "广东省",
            city: "广州市",
            current: 1,
            size: 10,
            ...params,
        };

        setCurrent(1);
        setSize(10);


        getRecommendationsList(data)
            .then((res) => {
                console.log('res.data.items', res.data.items);
                setRecommentList(res.data.items);
                const pagesCount = calculateTotalPages(res?.data?.counts, size);
                console.log('pagesCount', pagesCount);
                if (setRefreshing) {
                    setRefreshing(false);
                };
                setPages(pagesCount)
                noMore && noMore(true)
            })
            .catch(err => {
                if (setRefreshing) {
                    setRefreshing(false);
                };
                console.log('err', err);
            })
    };

    const loadingMoreRecommendList = function (params, loadingMore, setLoadingMore, noMore) {

        if (current == pages) {
            return noMore(false);
        };

        const data = {
            typeId: "2",
            province: "广东省",
            city: "广州市",
            current: Number(current + 1),
            size: 10,
            ...params,
        };


        setLoadingMore(true);

        getRecommendationsList(data)
            .then((res) => {
                const tmp  = [...recommentList, ...res.data.items]
                setRecommentList(tmp);
                setCurrent(current + 1);
                if (setLoadingMore) {
                    setLoadingMore(false);
                };
            })
            .catch(err => {
                if (setLoadingMore) {
                    setLoadingMore(false);
                };
                console.log('err', err);
            })
    };

    return (
        <View style={[styles.scene, { backgroundColor: '#F7F7F7' }]}>
            <View
               style={{ flex: 1 }}
            >
                {
                    length > 0 ? (
                        <View style={{ marginTop: 12, flex: 1, }}>
                            <TarjectoryActivityList
                                list={recommentList}
                                pullLoadData={getRecommentList}
                                loadMoreList={loadingMoreRecommendList}
                            />
                        </View>
                    ) : (
                        <View style={styles.emptyContainer}>
                            <Image source={empty_fan} style={{ width: "100%", height: "100%" }} />
                            <Text style={[{   transform: [{ translateX: -25 }] }, styles.empty_text]}>暂无浏览记录</Text>
                        </View>
                    )
                }
            </View>

            <Modal
                animationType="fade"
                transparent={true}
                visible={cancelConcern}
            >
                <TouchableOpacity
                    style={styles.cancelCenteredView}
                    onPress={() => setCancelConcern(false)}
                    activeOpacity={1}
                >
                    <View style={styles.cancelfollowContainer}>
                        <View>
                            <Text style={styles.followTitle}>取消关注</Text>
                        </View>
                        <View>
                            <Text style={styles.followCotent}>确定取消关注?</Text>
                        </View>
                        <View style={styles.footerContainer}>
                            <TouchableOpacity onPress={() => setCancelConcern(false)}>
                                <View style={[styles.footerBtn, styles.footerCancel]}>
                                    <Text style={{ color: "#2A2B30" }}>取消</Text>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => setCancelConcern(false)}>
                                <View style={[styles.footerBtn, styles.footerOk]}>
                                    <Text style={{ color: "#fff" }}>确定</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                </TouchableOpacity>
            </Modal>
        </View>
    );
};

const fanTowRoute = forwardRef(({ keywork }, ref) => {
    const [data, setData] = useState([]);
    const [refreshing, setRefreshing] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);
    const [page, setPage] = useState(1);
    const [totalPages, setTotalPages] = useState(0); //数据总量
    const [totalCount, setTotalCount] = useState(0); // 总分页数


    const login = useSelector((state: RootState) => state.login);

    const router = useRouter();

    const goActivityDetail = function (id) {
        router.push(`/activityDetail/${id}`)
    };


    useImperativeHandle(ref, () => ({
        fetchData
    }));

    console.log('searchTextsearchText', keywork);

    const fetchData = async ({ pageNum = 1, word = "" }, isRefreshing = false) => {
        if (isRefreshing) {
            setRefreshing(true);
        } else {
            setLoadingMore(true);
        };

        const requestData = {
            current: page,
            size: 10,
            word: word,
        };

        getSearchCoummunityListByRequest(requestData)
            .then((res: any) => {
                const newData = res?.data?.items;
                console.log('res', res);
                setData(prevData => (isRefreshing ? newData : [...prevData, ...newData]));
                setPage(pageNum);
                setTotalPages(res?.data?.counts);
                setTotalCount(res?.data?.pages)
                setRefreshing(false);
                setLoadingMore(false);
            })
            .catch(err => {
                setRefreshing(false);
                setLoadingMore(false);
                console.log('err', err);
            })
    };


    useEffect(() => {
        fetchData({ pageNum: 1, word: keywork }, true);
    }, [])

    // 自定义加载图标组件
    const RefreshControlHeader = ({ refreshing, text }) => (
        refreshing && (
            <View style={styles.refreshHeader}>
                <Text style={styles.refreshText}>{text}</Text>
            </View>
        )
    );

    const onRefresh = () => {
        fetchData({ pageNum: 1, word: keywork }, true);
    };

    const onLoadMore = () => {
        if (page == totalCount) {
            setRefreshing(false);
            setLoadingMore(false);
            return
        };
        if (page < totalPages) {
            fetchData({ pageNum: page + 1, word: keywork });
        }
    };


    const goJoinGroupPages = function (groupId) {
        router.push(`/registerGroup/applyJoinGroup/${groupId}`)
    };

    const goGroupDetail = function (groupId) {
        router.push(`/registerGroup/groupDetail/${groupId}`)
    };

    const ActivityItem = ({ item }) => {
        const { type } = item;
        // console.log('ActivityItemActivityItem', item);
        return (
            <View style={styles.groupContainer}>
                <View style={styles.groupStateContainer}>
                    <TouchableOpacity onPress={() => goGroupDetail(item.communityId)} style={{ position: "relative" }}>
                        <View style={styles.groupInfoWarp}>
                            <View style={styles.groupAvator}>
                                {/*<Text>ava</Text>*/}
                                <Image source={{ uri: item?.coverUrl }} style={{ width: "100%", height: '100%' }} />
                            </View>
                            <View style={styles.groupInfoCotent}>
                                <View>
                                    <Text style={styles.groupInfoTitle}>{ item?.name }</Text>
                                </View>
                                <View style={{ marginTop: 6 }}>
                                    <Text style={styles.groupInfoTotal}>成员数:{ item?.memberNum }人</Text>
                                </View>
                            </View>
                        </View>
                    </TouchableOpacity>
                    <View style={styles.groupCheck}>
                        <CheckBox
                            style={styles.selectCheckboxs}
                            tintColor="#E4E6EC"
                            lineWidth={1}
                            onCheckColor='#FB4B34'
                            onTintColor='#FB4B34'
                            onAnimationType="bounce"
                            offAnimationType="bounce"
                        />
                    </View>
                    {
                        item?.relationship == 1 && (
                            <TouchableOpacity onPress={() => goJoinGroupPages(item?.communityId)}>
                                <View style={styles.groupCreateBtn}>
                                    <Text style={styles.groupCreateBtnText}>加入</Text>
                                </View>
                            </TouchableOpacity>
                        )
                    }

                    {
                        item?.relationship == 2 && (
                            <TouchableOpacity onPress={() => goGroupDetail(item?.communityId)}>
                                <View style={styles.groupCreateBtn}>
                                    <Text style={styles.groupCreateBtnText}>审核中</Text>
                                </View>
                            </TouchableOpacity>
                        )
                    }

                    {
                        item?.relationship == 3 && (
                            <TouchableOpacity onPress={() => goGroupDetail(item?.communityId)}>
                                <View style={styles.groupCreateBtn}>
                                    <Text style={styles.groupCreateBtnText}>已加入</Text>
                                </View>
                            </TouchableOpacity>
                        )
                    }


                </View>
                {
                    item?.activityList.length > 0 && (
                        <View style={{ paddingHorizontal: 12 }}>
                            <CarouselComponent
                                loop
                                width={scaleSize(351)}
                                height={width * 0.32}
                                data={item?.activityList}
                                scrollAnimationDuration={1000}
                                initialScrollIndex={0}  // 设置初始滚动索引
                                renderItem={({ item }) => {
                                    return <SwiperActivityItemComponent showPrice={false} item={item} />
                                }}
                            />
                        </View>
                    )
                }

            </View>
        )
    };

    const ActivityItemCallBack = useCallback(({ item }) => (
        <ActivityItem item={item}/>
    ), []);

    return (
        <View style={styles.koneContainer}>
            <CustomFlatList
                data={data}
                keyExtractor={(item, index) => index.toString()}
                onRefresh={onRefresh}
                onLoadMore={onLoadMore}
                refreshing={refreshing}
                loadingMore={loadingMore}
                renderItem={ActivityItemCallBack}
                totalCount={totalCount}
                currentPage={page}
                totalPages={totalPages}
            />
        </View>
    );
});

// 自定义的 TabBar 组件
const CustomTabBar = ({ navigationState, position, setIndex }) => {
    // 创建指示器的动态宽度和位置
    const inputRange = navigationState.routes.map((_, i) => i);
    const layoutWith = scaleSize(240);
    const translateX = position.interpolate({
        inputRange,
        outputRange: inputRange.map(i => i * layoutWith / 2 + ((layoutWith / 2) - 26) / 2),
        // outputRange: [48, 162], // 这里的值需要根据实际情况计算
    });


    return (
        <View style={styles.tabHeader}>
            <View style={styles.tabBar}>
                {navigationState.routes.map((route, i) => (
                    <TouchableOpacity
                        key={route.key}
                        onPress={() => setIndex(i)}
                        style={styles.tabItem}>
                        <Text style={{color: navigationState.index === i ? '#EC6138' : 'black'}}>
                            {route.title}
                        </Text>
                    </TouchableOpacity>
                ))}
                {/* 自定义指示器 */}
                <Animated.View
                    style={[
                        styles.indicator,
                        {transform: [{translateX}]},
                        {width: scaleSize(26)} // 指示器的宽度
                    ]}
                />
            </View>
            <View style={styles.date}>
                <Text style={styles.dateText}>今天</Text>
            </View>
        </View>
    );
}

export default function myTrajectoryView() {
    const layout = useWindowDimensions();

    const [index, setIndex] = React.useState(0);
    const [routes] = React.useState([
        { key: 'first', title: '活动' },
        { key: 'second', title: '社群' },
    ]);

    const renderScene = SceneMap({
        first: fanRoute,
        second: fanTowRoute,
    });

    const router = useRouter();

    return (
        <>
            <Stack.Screen
                options={{
                    title: '我的轨迹', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#fff', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                }}
            />
            <TabView
                navigationState={{ index, routes }}
                renderScene={renderScene}
                onIndexChange={setIndex}
                initialLayout={{ width: layout.width }}
                renderTabBar={(props) => <CustomTabBar {...props} setIndex={setIndex} />} // 使用自定义的 TabBar
            />
            <View style={styles.bottomTool}>
                <View style={styles.botLeft}>
                    <CheckBox
                        style={styles.selectCheckbox}
                        tintColor="#E4E6EC"
                        lineWidth={1}
                        onCheckColor='#FB4B34'
                        onTintColor='#FB4B34'
                        onAnimationType="bounce"
                        offAnimationType="bounce"
                    />


                    <View style={styles.allSelect}>
                        <Text style={styles.allSelectText}>全选</Text>
                    </View>
                    <View style={styles.shu}>
                    </View>
                    <View style={styles.selectActivity}>
                        <Text style={styles.selectActivityText}>已选中<Text style={styles.activityNum}>1</Text>个活动</Text>
                    </View>
                </View>
                <TouchableOpacity>
                    <View style={styles.deleteBtn}>
                        <Text style={styles.deleteBtnText}>删除</Text>
                    </View>
                </TouchableOpacity>
            </View>
        </>
    );
}

const styles = StyleSheet.create({
    scene: {
        flex: 1,
        // justifyContent: 'center',
        // alignItems: 'center',
    },
    tabBar: {
        flexDirection: 'row',
        backgroundColor: 'white',
        position: 'relative', // 需要相对定位来放置指示器
        width:scaleSize(240),
        margin: "auto",
    },
    tabItem: {
        flex: 1,
        alignItems: 'center',
        paddingTop: 10,
        paddingBottom: 9,
        fontSize: 14,
        color: "#2A2B30"
    },
    indicator: {
        position: 'absolute',
        height: 3,
        backgroundColor: '#EC6138',
        bottom: 0,
        borderRadius: 5,
    },
    tabHeader: {
        backgroundColor: "#fff",
        borderBottomWidth: 1,
        borderBottomColor: "#F1F2F5"
    },
    fanContainer: {
        flexDirection: "row",
        marginLeft: 12,
        flex: 1,
        marginRight: 12,
        alignItems: "center",
        marginBottom: 20,
    },
    fanAvator: {
        width: scaleSize(46),
        height: scaleSize(46),
    },
    fanName: {
        flex: 1,
    },
    fanNameText: {
        fontSize: 14,
        color: "#3D3D3D",
        marginLeft: 10,
    },
    fanConcern: {
        width: 56,
        height: 26,
        borderRadius: 13,
        borderWidth: 1,
        borderStyle: "solid",
        borderColor: "#C0C3CE",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
    },
    fanTowConcern: {
        width: 56,
        height: 26,
        borderRadius: 13,
        borderWidth: 1,
        borderStyle: "solid",
        borderColor: "#EC6138",
        backgroundColor: "#EC6138",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
    },
    fanTwoConcernText: {
        color: "#fff",
        fontSize: 12,
    },
    fanConcernText: {
        color: "#C0C3CE",
        fontSize: 11,
    },

    cancelCenteredView: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(0,0,0,0.5)',  // 背景遮罩
    },
    cancelfollowContainer: {
        width: 296,
        height: 160,
        backgroundColor: "#fff",
        borderRadius: 8,
        padding: 24,
    },
    followTitle: {
        fontSize: 16,
        color: "#2A2B30",
        fontWeight: 400,
        textAlign: "center"
    },
    followCotent: {
        fontSize: 14,
        color: "#676978",
        textAlign: "center",
        marginTop: 14,
    },
    footerContainer: {
        flexDirection: "row",
        marginTop: 34,
        justifyContent: "space-between"
    },
    footerBtn: {
        width: 114,
        height: 38,
        borderRadius: 19,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
    },
    footerCancel: {
        backgroundColor: "#F7F8F9",
    },
    footerOk: {
        backgroundColor: "#EC6138",
    },
    emptyContainer: {
        marginTop: 98,
        position: "relative",
        width: scaleSize(220),
        height: scaleSize(220),
        margin: "auto",
    },
    empty_text: {
        left: '50%',
        marginTop: 160,
        position: 'absolute',
        color: "#9C9EAC",
        fontSize: 14,
    },
    date: {
        backgroundColor: "#fff",
        flexDirection: 'row',
        alignItems: "center",
        paddingVertical: 10,
        paddingLeft: 10,
    },
    dateText: {
        fontSize: 16,
        color: "#2A2B30",
    },
    bottomTool: {
        backgroundColor: "#fff",
        paddingBottom: 37,
        paddingTop: 8,
        flexDirection: "row",
        paddingLeft: 12,
        paddingRight: 16,
    },
    botLeft: {
        flexDirection: "row",
        alignItems: "center",
        flex: 1,
    },
    deleteBtn: {
        width: 80,
        height: 32,
        backgroundColor: "#EC6138",
        borderRadius: 20,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    deleteBtnText: {
        color: "#fff",
        fontSize: 14,
    },
    allSelect: {
        marginRight: 8,
    },
    shu: {
        width: 0.5,
        height: 8,
        backgroundColor: "#E4E6EC",
        marginRight: 8,
    },
    allSelectText: {
        color: "#676978",
        fontSize: 14,
    },
    selectActivity: {

    },
    selectActivityText: {
        color: "#676978",
        fontSize: 14,
    },
    activityNum: {
        color: "#EC6138",
        fontSize: 14,
    },
    selectCheckbox: {
        width: 18,
        height: 18,
        color: "#FB4B34",
        marginRight: 6,
    },
    groupStateContainer: {
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",

        paddingRight: 12,
    },
    groupInfoWarp: {
        flexDirection: 'row',
        alignItems: "center",
        marginTop: 16,
        marginBottom: 16,
        marginLeft: 24,
        marginRight: 12,
    },
    groupAvator: {
        width: scaleSize(52),
        height: scaleSize(52),
        borderRadius: 50,
        overflow: "hidden",
    },
    groupInfoCotent: {
        marginLeft: 10,
    },
    groupInfoTitle: {
        // fontWeight: "bold",
    },
    groupInfoTotal: {
        color: "#9C9EAC",
        fontSize: 12,
    },
    groupOut: {
        width: 56,
        height: 26,
        borderColor: "#EC6138",
        borderWidth: 1,
        borderRadius: 13,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    groupOutText: {
        color: "#EC6138",
        fontSize: 12,
    },

    groupCreateBtn: {
        width: 56,
        height: 26,
        backgroundColor: "#EC6138",
        borderRadius: 13,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    groupCreateBtnText: {
        color: "#fff",
        fontSize: 12,
    },
    groupContainer: {
        marginHorizontal: 12,
        backgroundColor:"#fff",
        marginBottom: 12,
        borderRadius: 8,
    },
    koneContainer: {
        // margin: 12,
        backgroundColor: "#F7F7F7",
        padding: 12,
        flex: 1,
    },
    groupCheck: {
        position: "absolute",
        top: 8,
        right: 2,
    },
    selectCheckboxs: {
        width: 13,
        height: 13,
        color: "#FB4B34",
        marginRight: 6,
    },
});
